<template>
  <div class="recommendation-page">
    <van-nav-bar
      title="智能推荐"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
      class="custom-nav-bar"
    />

    <div class="feature-intro">
      <div class="intro-content">
        <div class="intro-icon">🎯</div>
        <div class="intro-text">
          <h3>AI智能推荐</h3>
          <p>个性化内容推荐，发现你可能喜欢的精彩世界</p>
        </div>
      </div>
    </div>

    <!-- 推荐分类选择 -->
    <div class="category-section">
      <div class="category-tabs">
        <div
          v-for="category in categories"
          :key="category.id"
          :class="['category-tab', { active: activeCategory === category.id }]"
          @click="activeCategory = category.id"
        >
          <div class="tab-icon">{{ category.icon }}</div>
          <div class="tab-name">{{ category.name }}</div>
        </div>
      </div>
    </div>

    <!-- 快速推荐卡片 -->
    <div class="quick-recommendations">
      <div class="section-title">
        <h3>{{ currentCategory.name }}推荐</h3>
        <van-button size="small" @click="refreshRecommendations">
          <van-icon name="replay" />
          换一批
        </van-button>
      </div>

      <div class="recommendation-cards">
        <div
          v-for="item in currentRecommendations"
          :key="item.id"
          class="recommendation-card"
          @click="selectRecommendation(item)"
        >
          <div class="card-image">{{ item.emoji }}</div>
          <div class="card-content">
            <h4 class="card-title">{{ item.title }}</h4>
            <p class="card-desc">{{ item.description }}</p>
            <div class="card-tags">
              <span v-for="tag in item.tags" :key="tag" class="tag">{{ tag }}</span>
            </div>
            <div class="card-rating">
              <van-rate v-model="item.rating" readonly size="12" />
              <span class="rating-text">{{ item.rating }}/5</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 个性化推荐 -->
    <div class="personalized-section">
      <div class="input-section">
        <h3>🤖 个性化推荐</h3>
        <van-field
          v-model="preferences"
          placeholder="告诉我你的兴趣爱好、喜欢的类型..."
          type="textarea"
          rows="2"
          autosize
          :maxlength="200"
          show-word-limit
        />

        <!-- 智能功能 -->
        <div class="smart-features">
          <div class="feature-item" @click="showQuickPreferences">
            <van-icon name="star-o" />
            <span>兴趣标签</span>
          </div>
          <div class="feature-item" @click="showRecommendationHistory">
            <van-icon name="clock-o" />
            <span>推荐历史</span>
          </div>
          <div class="feature-item" @click="toggleDarkMode">
            <van-icon :name="isDarkMode ? 'sun-o' : 'moon-o'" />
            <span>{{ isDarkMode ? '浅色' : '深色' }}</span>
          </div>
          <div class="feature-item" @click="exportRecommendations">
            <van-icon name="down" />
            <span>导出收藏</span>
          </div>
        </div>

        <van-button
          type="primary"
          block
          :loading="isLoading"
          @click="getPersonalizedRecommendations"
          :disabled="!preferences.trim()"
        >
          获取专属推荐
        </van-button>
      </div>

      <div v-if="personalizedRecommendations" class="result-section">
        <div class="result-header">
          <h4>🎁 专属推荐</h4>
          <div class="result-actions">
            <van-button size="small" @click="copyRecommendations">复制</van-button>
            <van-button size="small" @click="saveRecommendations">收藏</van-button>
            <van-button size="small" @click="shareRecommendations">分享</van-button>
          </div>
        </div>
        <div class="recommendations-text">{{ personalizedRecommendations }}</div>
      </div>
    </div>

    <!-- 兴趣标签弹窗 -->
    <van-popup v-model:show="showPreferencesPopup" position="bottom" :style="{ height: '60%' }">
      <div class="preferences-popup">
        <div class="popup-header">
          <h3>选择兴趣标签</h3>
          <van-button size="small" @click="showPreferencesPopup = false">关闭</van-button>
        </div>
        <div class="popup-content">
          <div class="interest-categories">
            <div v-for="category in interestCategories" :key="category.name" class="interest-category">
              <h4>{{ category.icon }} {{ category.name }}</h4>
              <div class="interest-tags">
                <div
                  v-for="tag in category.tags"
                  :key="tag"
                  :class="['interest-tag', { selected: selectedTags.includes(tag) }]"
                  @click="toggleTag(tag)"
                >
                  {{ tag }}
                </div>
              </div>
            </div>
          </div>
          <div class="popup-footer">
            <van-button type="primary" block @click="applySelectedTags">
              应用选择 ({{ selectedTags.length }})
            </van-button>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 推荐历史弹窗 -->
    <van-popup v-model:show="showHistoryPopup" position="bottom" :style="{ height: '60%' }">
      <div class="history-popup">
        <div class="popup-header">
          <h3>推荐历史</h3>
          <div class="header-actions">
            <van-button size="small" @click="clearRecommendationHistory">清空</van-button>
            <van-button size="small" @click="showHistoryPopup = false">关闭</van-button>
          </div>
        </div>
        <div class="popup-content">
          <div v-if="recommendationHistory.length === 0" class="empty-history">
            <div class="empty-icon">🎯</div>
            <p>暂无推荐历史</p>
          </div>
          <div v-else class="history-list">
            <div
              v-for="(item, index) in recommendationHistory"
              :key="index"
              class="history-item"
              @click="selectHistoryItem(item)"
            >
              <div class="history-content">
                <div class="history-category">{{ item.category }}</div>
                <div class="history-title">{{ item.title || '个性化推荐' }}</div>
                <div class="history-preview">{{ item.content.slice(0, 50) }}...</div>
                <div class="history-time">{{ formatTime(item.timestamp) }}</div>
              </div>
              <van-icon name="arrow" />
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { showToast } from 'vant'
import aiService from '@/services/aiService'
import { saveUserData, loadUserData, getCurrentUserId, migrateOldData } from '@/utils/userDataManager'

const preferences = ref('')
const personalizedRecommendations = ref('')
const isLoading = ref(false)

// 新增功能状态
const activeCategory = ref('music')
const showPreferencesPopup = ref(false)
const showHistoryPopup = ref(false)
const isDarkMode = ref(false)
const selectedTags = ref<string[]>([])

// 本地存储功能
const recommendationHistory = ref<Array<{category: string, title: string, content: string, timestamp: number}>>([])

// 推荐分类
const categories = ref([
  { id: 'music', name: '音乐', icon: '🎵' },
  { id: 'movie', name: '电影', icon: '🎬' },
  { id: 'book', name: '书籍', icon: '📚' },
  { id: 'food', name: '美食', icon: '🍽️' },
  { id: 'travel', name: '旅游', icon: '✈️' },
  { id: 'game', name: '游戏', icon: '🎮' }
])

// 当前分类
const currentCategory = computed(() => {
  return categories.value.find(c => c.id === activeCategory.value) || categories.value[0]
})

// 推荐数据库
const recommendationDatabase = ref({
  music: [
    {
      id: 1,
      title: '《夜曲》- 周杰伦',
      description: '经典中文流行歌曲，旋律优美动人',
      emoji: '🎼',
      tags: ['流行', '中文', '经典'],
      rating: 4.8
    },
    {
      id: 2,
      title: '《Shape of You》- Ed Sheeran',
      description: '欧美流行金曲，节奏感强烈',
      emoji: '🎤',
      tags: ['欧美', '流行', '热门'],
      rating: 4.7
    },
    {
      id: 3,
      title: '《千本樱》- 初音未来',
      description: '日系电子音乐，充满活力',
      emoji: '🌸',
      tags: ['电子', '日系', '动感'],
      rating: 4.6
    }
  ],
  movie: [
    {
      id: 1,
      title: '《肖申克的救赎》',
      description: '经典剧情片，关于希望与自由',
      emoji: '🎭',
      tags: ['剧情', '经典', '励志'],
      rating: 4.9
    },
    {
      id: 2,
      title: '《千与千寻》',
      description: '宫崎骏动画杰作，奇幻冒险',
      emoji: '🏰',
      tags: ['动画', '奇幻', '治愈'],
      rating: 4.8
    },
    {
      id: 3,
      title: '《复仇者联盟》',
      description: '超级英雄大片，视觉盛宴',
      emoji: '🦸',
      tags: ['动作', '科幻', '英雄'],
      rating: 4.5
    }
  ],
  book: [
    {
      id: 1,
      title: '《三体》- 刘慈欣',
      description: '科幻小说巨作，宇宙文明思考',
      emoji: '🌌',
      tags: ['科幻', '中文', '深度'],
      rating: 4.8
    },
    {
      id: 2,
      title: '《哈利·波特》系列',
      description: '魔法世界冒险，成长与友谊',
      emoji: '⚡',
      tags: ['奇幻', '冒险', '成长'],
      rating: 4.7
    },
    {
      id: 3,
      title: '《百年孤独》',
      description: '魔幻现实主义经典，拉美文学',
      emoji: '🏛️',
      tags: ['文学', '经典', '深度'],
      rating: 4.6
    }
  ],
  food: [
    {
      id: 1,
      title: '重庆火锅',
      description: '麻辣鲜香，川渝特色美食',
      emoji: '🍲',
      tags: ['川菜', '麻辣', '聚餐'],
      rating: 4.8
    },
    {
      id: 2,
      title: '日式拉面',
      description: '浓郁汤头，日本国民美食',
      emoji: '🍜',
      tags: ['日料', '面食', '暖胃'],
      rating: 4.6
    },
    {
      id: 3,
      title: '意大利披萨',
      description: '芝士拉丝，西式经典',
      emoji: '🍕',
      tags: ['西餐', '芝士', '分享'],
      rating: 4.5
    }
  ],
  travel: [
    {
      id: 1,
      title: '马尔代夫',
      description: '碧海蓝天，度假天堂',
      emoji: '🏝️',
      tags: ['海岛', '度假', '浪漫'],
      rating: 4.9
    },
    {
      id: 2,
      title: '京都',
      description: '古都风情，樱花与寺庙',
      emoji: '🏯',
      tags: ['文化', '古迹', '日本'],
      rating: 4.7
    },
    {
      id: 3,
      title: '巴黎',
      description: '浪漫之都，艺术与时尚',
      emoji: '🗼',
      tags: ['浪漫', '艺术', '欧洲'],
      rating: 4.6
    }
  ],
  game: [
    {
      id: 1,
      title: '《原神》',
      description: '开放世界冒险，精美画面',
      emoji: '⚔️',
      tags: ['RPG', '开放世界', '二次元'],
      rating: 4.7
    },
    {
      id: 2,
      title: '《王者荣耀》',
      description: 'MOBA竞技，团队合作',
      emoji: '👑',
      tags: ['MOBA', '竞技', '团队'],
      rating: 4.5
    },
    {
      id: 3,
      title: '《塞尔达传说》',
      description: '任天堂经典，探索冒险',
      emoji: '🛡️',
      tags: ['冒险', '探索', '任天堂'],
      rating: 4.8
    }
  ]
})

// 当前推荐
const currentRecommendations = computed(() => {
  return recommendationDatabase.value[activeCategory.value as keyof typeof recommendationDatabase.value] || []
})

// 兴趣分类
const interestCategories = ref([
  {
    name: '娱乐',
    icon: '🎭',
    tags: ['音乐', '电影', '电视剧', '综艺', '动漫', '游戏', '直播', '短视频']
  },
  {
    name: '学习',
    icon: '📚',
    tags: ['编程', '设计', '语言', '考试', '技能', '课程', '书籍', '文档']
  },
  {
    name: '生活',
    icon: '🏠',
    tags: ['美食', '旅游', '购物', '健身', '美容', '家居', '宠物', '摄影']
  },
  {
    name: '兴趣',
    icon: '🎨',
    tags: ['绘画', '音乐', '舞蹈', '手工', '收藏', '园艺', '运动', '阅读']
  }
])

// 从本地存储加载数据
const loadLocalData = () => {
  try {
    const userId = getCurrentUserId()
    if (!userId) {
      console.warn('⚠️ 用户未登录，无法加载个人数据')
      return
    }

    // 迁移旧数据（如果存在）
    migrateOldData('recommendation', [
      { oldKey: 'recommendation_history', dataType: 'history' },
      { oldKey: 'recommendation_selectedTags', dataType: 'selectedTags' },
      { oldKey: 'recommendation_darkMode', dataType: 'darkMode' }
    ])

    // 加载用户专属数据
    recommendationHistory.value = loadUserData('recommendation', 'history', [])
    selectedTags.value = loadUserData('recommendation', 'selectedTags', [])
    isDarkMode.value = loadUserData('recommendation', 'darkMode', false)

    // 应用深色模式
    document.documentElement.classList.toggle('dark-mode', isDarkMode.value)

    console.log(`✅ 智能推荐数据已加载 - 用户ID: ${userId}`)
  } catch (error) {
    console.error('❌ 加载本地数据失败:', error)
  }
}

// 保存到本地存储
const saveToLocal = (key: string, data: any) => {
  const success = saveUserData('recommendation', key, data)
  if (!success) {
    console.warn('⚠️ 保存数据失败，用户可能未登录')
  }
}

// 刷新推荐
const refreshRecommendations = () => {
  // 随机打乱当前分类的推荐
  const current = recommendationDatabase.value[activeCategory.value as keyof typeof recommendationDatabase.value]
  if (current) {
    current.sort(() => Math.random() - 0.5)
  }
  showToast('已为您刷新推荐')
}

// 选择推荐项
const selectRecommendation = (item: any) => {
  preferences.value = `我对${item.title}很感兴趣，请推荐类似的内容`
  nextTick(() => {
    getPersonalizedRecommendations()
  })
}

// 显示兴趣标签
const showQuickPreferences = () => {
  showPreferencesPopup.value = true
}

// 切换标签选择
const toggleTag = (tag: string) => {
  const index = selectedTags.value.indexOf(tag)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tag)
  }
}

// 应用选择的标签
const applySelectedTags = () => {
  if (selectedTags.value.length > 0) {
    preferences.value = `我的兴趣包括：${selectedTags.value.join('、')}`
    saveToLocal('selectedTags', selectedTags.value)
    showPreferencesPopup.value = false
    showToast(`已选择${selectedTags.value.length}个兴趣标签`)
  } else {
    showToast('请至少选择一个兴趣标签')
  }
}

// 显示推荐历史
const showRecommendationHistory = () => {
  showHistoryPopup.value = true
}

// 选择历史项目
const selectHistoryItem = (item: any) => {
  preferences.value = `请基于之前的推荐继续推荐：${item.title}`
  personalizedRecommendations.value = item.content
  showHistoryPopup.value = false
}

// 清空推荐历史
const clearRecommendationHistory = () => {
  recommendationHistory.value = []
  saveToLocal('history', recommendationHistory.value)
  showToast('推荐历史已清空')
}

// 切换深色模式
const toggleDarkMode = () => {
  isDarkMode.value = !isDarkMode.value
  document.documentElement.classList.toggle('dark-mode', isDarkMode.value)
  saveToLocal('darkMode', isDarkMode.value)
  showToast(isDarkMode.value ? '已切换到深色模式' : '已切换到浅色模式')
}

// 复制推荐
const copyRecommendations = () => {
  if (personalizedRecommendations.value) {
    navigator.clipboard.writeText(personalizedRecommendations.value)
    showToast('推荐内容已复制')
  }
}

// 保存推荐
const saveRecommendations = () => {
  if (personalizedRecommendations.value) {
    const newRecommendation = {
      category: currentCategory.value.name,
      title: preferences.value.slice(0, 30) + '...',
      content: personalizedRecommendations.value,
      timestamp: Date.now()
    }

    recommendationHistory.value.unshift(newRecommendation)
    if (recommendationHistory.value.length > 30) {
      recommendationHistory.value = recommendationHistory.value.slice(0, 30)
    }
    saveToLocal('history', recommendationHistory.value)
    showToast('推荐已保存到历史记录')
  }
}

// 分享推荐
const shareRecommendations = () => {
  if (personalizedRecommendations.value) {
    if (navigator.share) {
      navigator.share({
        title: 'AI智能推荐',
        text: personalizedRecommendations.value
      })
    } else {
      copyRecommendations()
      showToast('推荐内容已复制，可以分享给朋友')
    }
  }
}

// 导出推荐
const exportRecommendations = () => {
  if (recommendationHistory.value.length === 0) {
    showToast('暂无推荐记录可导出')
    return
  }

  const content = recommendationHistory.value.map(item => {
    const time = new Date(item.timestamp).toLocaleString()
    return `[${time}] ${item.category} - ${item.title}\n${item.content}`
  }).join('\n\n' + '='.repeat(50) + '\n\n')

  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `AI推荐收藏-${new Date().toLocaleDateString()}.txt`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)

  showToast('推荐收藏已导出到文件')
}

// 格式化时间
const formatTime = (timestamp: number) => {
  const now = Date.now()
  const diff = now - timestamp

  if (diff < 1000 * 60) {
    return '刚刚'
  } else if (diff < 1000 * 60 * 60) {
    return `${Math.floor(diff / (1000 * 60))}分钟前`
  } else if (diff < 1000 * 60 * 60 * 24) {
    return `${Math.floor(diff / (1000 * 60 * 60))}小时前`
  } else {
    return new Date(timestamp).toLocaleDateString()
  }
}

const getPersonalizedRecommendations = async () => {
  if (!preferences.value.trim()) return

  isLoading.value = true
  personalizedRecommendations.value = ''

  let accumulatedText = ''

  try {
    console.log('🚀 开始流式推荐:', preferences.value)

    // 使用流式输出
    await aiService.recommendationStream(
      12345,
      preferences.value,
      // onMessage回调
      (content: string) => {
        console.log('📝 收到推荐内容:', content)
        accumulatedText += content
        personalizedRecommendations.value = accumulatedText
      },
      // onComplete回调
      () => {
        console.log('✅ 流式推荐完成')
        // 自动保存到历史记录
        saveRecommendations()
        isLoading.value = false
      },
      // onError回调
      async (error: any) => {
        console.error('❌ 流式推荐失败，尝试非流式推荐:', error)

        // 流式输出失败，尝试非流式输出
        try {
          const response = await aiService.recommendation(12345, preferences.value, '通用')
          if (response.code === 200) {
            personalizedRecommendations.value = response.data || '推荐生成完成！'
          } else {
            personalizedRecommendations.value = '推荐失败，请重试。'
            showToast('推荐失败')
          }
        } catch (fallbackError) {
          console.error('非流式输出也失败:', fallbackError)
          personalizedRecommendations.value = '推荐失败，请重试。'
          showToast('推荐失败')
        }

        // 自动保存到历史记录
        saveRecommendations()
        isLoading.value = false
      }
    )

  } catch (error) {
    console.error('推荐失败:', error)

    // 备选方案：直接调用非流式API
    try {
      const response = await aiService.recommendation(12345, preferences.value, '通用')
      if (response.code === 200) {
        personalizedRecommendations.value = response.data || '推荐生成完成！'
      } else {
        personalizedRecommendations.value = '推荐失败，请重试。'
        showToast('推荐失败')
      }
    } catch (fallbackError) {
      console.error('备选方案失败:', fallbackError)
      personalizedRecommendations.value = '推荐失败，请重试。'
      showToast('推荐失败')
    }

    // 自动保存到历史记录
    saveRecommendations()
    isLoading.value = false
  }
}

// 已删除模拟数据生成函数，现在使用真实API

onMounted(() => {
  // 加载本地数据
  loadLocalData()
})
</script>

<style scoped>
.recommendation-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.custom-nav-bar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.feature-intro {
  margin: 16px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  backdrop-filter: blur(10px);
}

.intro-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.intro-icon {
  font-size: 40px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(67, 233, 123, 0.1);
  border-radius: 16px;
}

.intro-text h3 {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.intro-text p {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.recommendation-container {
  padding: 16px;
}

.input-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 16px;
}

.result-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
}

.result-section h4 {
  margin: 0 0 16px 0;
  color: #2c3e50;
}

.recommendations-text {
  font-size: 14px;
  line-height: 1.6;
  color: #2c3e50;
}

/* 分类选择区域 */
.category-section {
  margin: 16px 0;
}

.category-tabs {
  display: flex;
  gap: 8px;
  overflow-x: auto;
  padding: 8px 0;
}

.category-tab {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid #e2e8f0;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  min-width: 80px;
}

.category-tab:hover {
  background: #f0fdf4;
  border-color: #22c55e;
  transform: translateY(-2px);
}

.category-tab.active {
  background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
  border-color: #22c55e;
  color: white;
  box-shadow: 0 4px 12px rgba(34, 197, 94, 0.3);
}

.tab-icon {
  font-size: 20px;
}

.tab-name {
  font-size: 12px;
  font-weight: 500;
}

/* 快速推荐区域 */
.quick-recommendations {
  margin: 20px 0;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.recommendation-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
}

.recommendation-card {
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid #e2e8f0;
  border-radius: 16px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.recommendation-card:hover {
  background: #f0fdf4;
  border-color: #22c55e;
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(34, 197, 94, 0.15);
}

.card-image {
  font-size: 32px;
  text-align: center;
  margin-bottom: 12px;
}

.card-content {
  text-align: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 8px 0;
}

.card-desc {
  font-size: 14px;
  color: #64748b;
  margin: 0 0 12px 0;
  line-height: 1.4;
}

.card-tags {
  display: flex;
  gap: 6px;
  justify-content: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.tag {
  padding: 4px 8px;
  background: #f1f5f9;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  font-size: 12px;
  color: #64748b;
}

.card-rating {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.rating-text {
  font-size: 12px;
  color: #64748b;
}

/* 个性化推荐区域 */
.personalized-section {
  margin-top: 24px;
}

.personalized-section h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

/* 智能功能区域 */
.smart-features {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  margin: 16px 0;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 12px 8px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
  color: #64748b;
}

.feature-item:hover {
  background: #f0fdf4;
  border-color: #22c55e;
  color: #22c55e;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(34, 197, 94, 0.2);
}

.feature-item .van-icon {
  font-size: 18px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.result-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.result-actions {
  display: flex;
  gap: 8px;
}

/* 弹窗样式 */
.preferences-popup,
.history-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e2e8f0;
  background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
}

.popup-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.popup-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #f8fafc;
}

.interest-categories {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.interest-category h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.interest-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.interest-tag {
  padding: 8px 12px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  color: #64748b;
}

.interest-tag:hover {
  border-color: #22c55e;
  background: #f0fdf4;
}

.interest-tag.selected {
  background: #22c55e;
  border-color: #22c55e;
  color: white;
}

.popup-footer {
  padding: 16px;
  border-top: 1px solid #e2e8f0;
  background: white;
}

/* 历史记录样式 */
.empty-history {
  text-align: center;
  padding: 40px 20px;
  color: #64748b;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.history-item:hover {
  background: #f0fdf4;
  border-color: #22c55e;
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(34, 197, 94, 0.2);
}

.history-content {
  flex: 1;
}

.history-category {
  font-size: 12px;
  color: #22c55e;
  font-weight: 500;
  margin-bottom: 4px;
}

.history-title {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
  margin-bottom: 4px;
}

.history-preview {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 4px;
  line-height: 1.3;
}

.history-time {
  font-size: 12px;
  color: #94a3b8;
}

/* 深色模式支持 */
:global(.dark-mode) .recommendation-page {
  background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
}

:global(.dark-mode) .category-tab {
  background: rgba(71, 85, 105, 0.9);
  border-color: #64748b;
  color: #cbd5e1;
}

:global(.dark-mode) .category-tab:hover {
  background: #15803d;
  border-color: #22c55e;
  color: white;
}

:global(.dark-mode) .recommendation-card,
:global(.dark-mode) .result-section {
  background: rgba(51, 65, 85, 0.95);
  border-color: #475569;
}

:global(.dark-mode) .feature-item {
  background: rgba(71, 85, 105, 0.9);
  border-color: #64748b;
  color: #cbd5e1;
}

:global(.dark-mode) .feature-item:hover {
  background: #15803d;
  border-color: #22c55e;
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .recommendation-cards {
    grid-template-columns: 1fr;
  }

  .smart-features {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }

  .feature-item {
    padding: 16px 12px;
  }

  .category-tabs {
    gap: 6px;
  }

  .category-tab {
    min-width: 70px;
    padding: 10px 12px;
  }

  .result-actions {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .section-title {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .smart-features {
    grid-template-columns: repeat(2, 1fr);
  }

  .feature-item {
    font-size: 11px;
    padding: 10px 6px;
  }

  .interest-tags {
    gap: 6px;
  }

  .interest-tag {
    padding: 6px 10px;
    font-size: 13px;
  }
}
</style>
